package solutions.ferpa.ztest.intf;

import br.com.telescope.adsrt.dom.DomFlag;
import br.com.telescope.adsrt.dom.DomId;
import br.com.telescope.adsrt.dom.DomInteger;
import br.com.telescope.adsrt.dom.DomText;
import br.com.telescope.adsrt.dom.DomTextLong;
import br.com.telescope.adsrt.dom.DomUpper;
import br.com.telescope.adsrt.lib.*;
import br.com.telescope.t2.AccessPolicy;
import br.com.telescope.t2.ServiceModel;
import br.com.telescope.t2.ServiceUrlManager;
import br.com.telescope.t2.config.Config;
import br.com.telescope.t2.exception.ApplicationRuntimeException;
import br.com.telescope.t2.feature.CustomFeature;
import br.com.telescope.util.URLParameters;
import java.io.UnsupportedEncodingException;
import solutions.ferpa.ztest.ent.*;

/**
 * Menus.
 * <p>
 * Interface de navegação nos menus para dispositivos simples.
 * <P>
 * Telescope origin: RTMENU.LST_MENU
 * <P>
 * Base entity: RTMENU.MENUS
 * <P>
 * @author TELESCOPE - Build task T2 Web Interface Generator
 * <P>
 * @version 0.1
 */
public class LstMenu extends ServiceModel {
    
    // <editor-fold defaultstate="collapsed" desc="Generated Code">
    public static final String GLOBAL_NAME = "RTMENU.LST_MENU";
    
    @Override
    public String globalName() {
        return GLOBAL_NAME;
    }
    
    {
        setTitle("Menus");
    }
    
    protected EntMenus base;
    protected EntMenus rec; // NEED_TJW1_COMPATIBILITY
    
    // Record items
    private DomTextLong aDescricao;
    private DomId aId;
    private DomUpper aMenu;
    private DomInteger aSequencia;
    private DomId aSistemaId;
    private DomText aTitulo;
    private DomFlag aTopo;
    
    // Query items
    
    @Override
    public String getBaseSql() {
        return "select BASE.*"
                + " from MENUS BASE";
    }
    
    @Override
    public void initAttributes() {
        
        aDescricao = new DomTextLong();
        aDescricao.context(ctx).name("DESCRICAO").label("Descrição");
        
        aId = new DomId();
        aId.context(ctx).name("ID").label("Id");
        
        aMenu = new DomUpper();
        aMenu.context(ctx).name("MENU").label("Menu");
        
        aSequencia = new DomInteger();
        aSequencia.context(ctx).name("SEQUENCIA").label("Sequência");
        aSequencia.setDefaultValue("50");
        
        aSistemaId = new DomId();
        aSistemaId.context(ctx).name("SISTEMA_ID").label("Sistema (DEPRECIADO)");
        
        aTitulo = new DomText();
        aTitulo.context(ctx).name("TITULO").label("Título");
        
        aTopo = new DomFlag();
        aTopo.context(ctx).name("TOPO").label("Topo");
        aTopo.setDefaultValue("N");
        
    }
    
    @Override
    public String getQueryPkColumn() {
        return "BASE.ID";
    }
    
    @Override
    public void setId(String value) {
        this.aId.setValue(value);
    }
    
    @Override
    public EntMenus getRecord() {
        if (base == null) {
            base = new EntMenus(ctx);
            rec = base;
        }
        return this.base;
    }
    
    @Override
    public String getDefaultOrderBy() {
        return "";
    }
    // </editor-fold>
    
    // <editor-fold defaultstate="collapsed" desc="CUSTOM">
    public class FCustom extends CustomFeature {
        
        @Override
        public void initForm() {
        }
        
        @Override
        public int getAccessPolicy() {
            return AccessPolicy.PUBLIC;
        }
        
        @Override
        public void preDisplay() {
            try {
                montarListaMenus();
            } catch (AdsException ex) {
                throw new ApplicationRuntimeException(ex);
            }
        }
        
        {
            setFeatureName("CUSTOM");
            setPrimary(false);
        }
    }
    // </editor-fold>
    
    // <editor-fold defaultstate="collapsed" desc="initFeatures">
    
    @Override
    protected void initFeatures() {
        addFeature(new FCustom());
        super.initFeatures();
    }
    
    @Override
    public String getDefaultFeature() {
        return "CUSTOM";
    }
    // </editor-fold>
    
    // <editor-fold defaultstate="collapsed" desc="Getters and Setters">
    
    public String getDescricao() {
        return aDescricao.getValue();
    }
    
    public void setDescricao(String value) {
        this.aDescricao.setValue(value);
    }
    
    @Override
    public Long getId() {
        return aId.getValue();
    }
    
    public void setId(Long value) {
        this.aId.setValue(value);
    }
    
    public String getMenu() {
        return aMenu.getValue();
    }
    
    public void setMenu(String value) {
        this.aMenu.setValue(value);
    }
    
    public Integer getSequencia() {
        return aSequencia.getValue();
    }
    
    public void setSequencia(Integer value) {
        this.aSequencia.setValue(value);
    }
    
    public Long getSistemaId() {
        return aSistemaId.getValue();
    }
    
    public void setSistemaId(Long value) {
        this.aSistemaId.setValue(value);
    }
    
    public String getTitulo() {
        return aTitulo.getValue();
    }
    
    public void setTitulo(String value) {
        this.aTitulo.setValue(value);
    }
    
    public String getTopo() {
        return aTopo.getValue();
    }
    
    public void setTopo(String value) {
        this.aTopo.setValue(value);
    }
    // </editor-fold>
    
    /**
     * Montar lista de menus.
     * <p>
     * Monta uma lista com os menus disponível para aquele usuário caso o 
     * menu que ele clique possuí submenus, é gerado uma nova lista com os 
     * menus daquele submenu
     */
    private void montarListaMenus() throws AdsException {
        // <user-code id="5536490" parentId="5536488" hashcode="-6da0dba7" length="1950">
        // import br.com.telescope.util.URLParameters;
        // import java.io.UnsupportedEncodingException;
        // import br.com.telescope.t2.ServiceUrlManager;
        // import br.com.telescope.t2.config.Config;
        
        EntMenus menu = new EntMenus(ctx);
        EntItensMenus item = new EntItensMenus(ctx);
        try {
            Config config = Config.getInstance();
            menu.findByMenu(ctx.getParameter("SUB_MENU").isEmpty() ? config.getParameter("RT." + ctx.getControllerName() + ".MENU_DEFAULT", config.getParameter("RT.MENU.TOP_MENUS", "COLETORES")) : ctx.getParameter("SUB_MENU"));
            item = menu.findAllItensMenusMenu();
        
            ctx.p("<ul data-navigation class=\"menu\">");
        
            setTitle(menu.valueOfTitulo());
        
            while (item.next()) {
                if (item.getUrl().isNotNull() && item.valueOfAtivo().equals("S")) {
                    ctx.p("<li><a href=\"" + item.valueOfUrl() + "\">" + item.valueOfTitulo() + "</a></li>");
                } else if (item.getSubMenuId().isNotNull()) {
                    URLParameters parms = new URLParameters();
                    parms.put("SUB_MENU", item.findSubMenu().valueOfMenu());
                    StringBuilder out = new StringBuilder(ServiceUrlManager.getInstance().getUriForService("RTMENU.LST_MENU"));
                    try {
                        if (verificaUsuarioAcessoMenu(item.findSubMenu().valueOfMenu())) {
                            ctx.p("<li><a href=\"" + out + "?" + parms.getURLParameters() + "\">" + item.valueOfTitulo() + "</a></li>");
                        }
                    } catch (UnsupportedEncodingException ex) { }
                } else {
                    if ((item.valueOfPublico().equals("S") || (ctx.userHasAccessToService(item.findInterface().valueOfNome())) && item.valueOfAtivo().equals("S"))) {
                        ctx.p("<li><a href=\"" + ServiceUrlManager.getInstance().getUriForService(item.findInterface().valueOfNome()) + "\">" + item.valueOfTitulo() + "</a></li>");
                    }
                }
            }
        
            ctx.p("</ul>");
        
        } catch (RecordNotFoundException ex) {
        
        }
        
        // </user-code>
    }
    
    /**
     * Verifica se usuario tem acesso ao menu.
     * <p>
     * Verifica se o usuário tem acesso a algum item do submenu
     */
    private Boolean verificaUsuarioAcessoMenu(String submenu) throws AdsException {
        // <user-code id="5536497" parentId="5536495" hashcode="6138097c" length="822">
        EntMenus menu = new EntMenus(ctx);
        EntItensMenus item = new EntItensMenus(ctx);
        
        try {
            menu.findByMenu(submenu);
            item = menu.findAllItensMenusMenu();
            
            while (item.next()) {
                if (item.valueOfPublico().equals("S")) {
                    return true;
                } else {
                    if (item.getSubMenuId().isNotNull()) {
                        if (verificaUsuarioAcessoMenu(item.findSubMenu().valueOfMenu())) {
                            return true;
                        }
                    } else if (item.getInterfaceId().isNotNull()) {
                        if (ctx.userHasAccessToService(item.findInterface().valueOfNome())) {
                            return true;
                        }
                    } else {
                        return true;
                    }
                }
            }
        } catch (RecordNotFoundException ex) {}
        
        return false;
        // </user-code>
    }
}
